package com.quizzapp.activity;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.example.quizzapp.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.quizzapp.bean.Usuario;
import com.quizzapp.util.ConnectionServiceBO;
import com.quizzapp.util.UserBO;

public class Login extends Activity implements IHttpResponseImpl {
	private EditText un, pw;
	private ConnectionServiceBO connectionServiceBO;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// verifyDeviceRegistered();
		verifyUserLogged();
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.un = (EditText) findViewById(R.id.et_un);
		this.pw = (EditText) findViewById(R.id.et_pw);
		this.connectionServiceBO = new ConnectionServiceBO(this);
	}

	public void onClickLogin(View view) {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("LogUser", un.getText().toString());
		parameters.put("password", pw.getText().toString());
		this.connectionServiceBO.setServiceName("RecuperarUsuarioV1");
		this.connectionServiceBO.setParameters(parameters);
		this.connectionServiceBO.execute();
	}

	@Override
	public void httpResult(String result) {
		try {
			if (result.indexOf('{') > -1) {
				JSONObject json = new JSONObject(result);

				Usuario usuario = new Usuario();
				usuario.setId(json.getString("idUsuario"));
				usuario.setNombre(json.getString("Nombre"));
				usuario.setLogUser(json.getString("logUser"));
				usuario.setPassword(json.getString("password"));
				usuario.setApellido1(json.getString("Apellido1"));
				usuario.setApellido2(json.getString("Apellido2"));

				// Accedemos al listado
				UserBO.writeName(this.getApplicationContext(), usuario.getNombreCompleto());
				UserBO.writeId(this, usuario.getId());
				accessApplication();
			}
			else {
				connectionServiceBO.showMessage("Error", result);
			}
		}
		catch (JSONException e) {
			connectionServiceBO.showMessage("Error", "Error de acceso");
			Log.d("HTTPCLIENT", e.getLocalizedMessage());
		}
	}

	public void onClickAnonimous(View view) {
		accessApplication();
	}

	public void onClickRegister(View view) {
		Intent intent = new Intent(getApplicationContext(), Registry.class);
		startActivity(intent);
	}

	private void verifyDeviceRegistered() {
		String uuid = UserBO.readUuid(this);
		if (uuid == null) {
			uuid = UUID.randomUUID().toString();

			JSONObject jsonObject = new JSONObject();
			try {
				jsonObject.put("uuid", uuid);
				AsyncHttpClient client = new AsyncHttpClient();
				StringEntity entity = new StringEntity(jsonObject.toString());

				String contentType = "application/json; charset=UTF-8";

				String restApiUri = /* prop.getProperty("serverUri") + */"registroDispositivo";
				client.post(getApplicationContext(), restApiUri, entity, contentType, new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(JSONObject jObject) {
						try {
							if (jObject.has("error")) {
								connectionServiceBO.showMessage("Error de acceso", jObject.getString("mensaje"));
							}
							else {
								UserBO.writeUuid(getApplicationContext(), jObject.getString("parameter"));
							}
						}
						catch (JSONException e) {
							Log.d("tag", "Fallo al registrar el dispositivo");
						}
					}

					@Override
					public void onFailure(Throwable arg0) {
						connectionServiceBO.showMessage("Error de acceso", "Se ha producido un error de acceso. Vuelva a intentarlo.");
					}
				});
			}
			catch (JSONException e) {
				Log.d("tag", "Fallo al registrar el dispositivo");
			}
			catch (UnsupportedEncodingException e) {
				Log.d("tag", "Fallo al registrar el dispositivo");
			}
		}
	}

	private void accessApplication() {
		Intent intent = new Intent(this, List.class);
		startActivity(intent);
	}

	private void verifyUserLogged() {
		String name = UserBO.readName(this);
		if (name != null && name.length() > 0) {
			accessApplication();
		}
	}
}
